﻿/**
 * Copyright (C) 2012-2013 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using NGuice.Inject.Spi;
using NGuice.Inject.Internal.Util;

namespace NGuice.Inject.Internal
{
    //complete！
    /// <summary>
    /// 设置可注入的域
    /// </summary>
    internal sealed class SingleFieldInjector : SingleMemberInjector
    {
        internal readonly FieldInfo field;
        internal readonly InjectionPoint injectionPoint;
        internal readonly Dependency dependency;
        internal readonly InternalFactory factory;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="injector"></param>
        /// <param name="injectionPoint"></param>
        /// <param name="errors"></param>
        /// <exception cref="ErrorsException"></exception>
        public SingleFieldInjector(InjectorImpl injector, InjectionPoint injectionPoint, Errors errors)
        {
            this.injectionPoint = injectionPoint;
            this.field = (FieldInfo)injectionPoint.Member;
            this.dependency = injectionPoint.Dependencies[0];

            // Ewwwww...
            //field.SetAccessible(true);
            factory = injector.GetInternalFactory(dependency.Key, errors, InjectorImpl.JitLimitation.NO_JIT);
        }


        public void Inject(Errors errors, InternalContext context, object o)
        {
            errors = errors.WithSource(dependency);

            Dependency previous = context.SetDependency(dependency);
            try
            {
                object value = factory.Get(errors, context, dependency, false);
                field.SetValue(o, value);
            }
            catch (ErrorsException e)
            {
                errors.WithSource(injectionPoint).Merge(e.Errors);
            }
            catch (FieldAccessException e)
            {
                throw new AssertionError("a security manager is blocking us to set filed value", e); // a security manager is blocking us, we're hosed
            }
            finally
            {
                context.SetDependency(previous);
            }
        }

        public InjectionPoint GetInjectionPoint()
        {
            return injectionPoint;
        }
    }
}
